package main

import (
	"dataserver-demo/core"
	dm "dataserver-demo/driver/dm"
	"dataserver-demo/driver/gbase"
	"fmt"
	"log"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"

	"gorm.io/gorm"
)

var DB *gorm.DB

const (
	Driver = "dm"
)

func initDB() (*gorm.DB, error) {

	var err error

	switch Driver {
	case "mysql":
		log.Println("初始化 mysql")
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", "root", "root", "158.100.6.22", "3306", "dataserver")
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	case "kingbase": //人大金仓
		log.Println("初始化 kingbase")
		dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "192.168.140.237", 54321, "dataserver", "vrv123456", "dataserver")
		DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
		DB.Exec("SET CLIENT_ENCODING TO 'UTF8'") //设置编码格式
	case "dm": //达梦
		log.Println("初始化 dm")
		dsn := fmt.Sprintf("%s://%s:%s@%s:%s", "dm", "dataserver", "vrv123456", "192.168.140.237", "30236")
		DB, err = gorm.Open(dm.Open(dsn), &gorm.Config{})
	case "oscar": //神州通用(试用版到期无法下载)
		log.Println("初始化 oscar")
		dsn := fmt.Sprintf("%s/%s@%s:%s/%s", "SYSDBA", "szoscar55", "192.168.140.237", "2003", "OSRDB")
		DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
	case "gbase": //南大通用（镜像运行失败且无日志）
		log.Println("初始化 gbase")
		dsn := fmt.Sprintf("DRIVER=%s;DB=%s;UID=%s;pwd=%s;servername=%s;DB_LOCALE=zh_CN.utf8;CLIENT_LOCALE=zh_CN.utf8;NEWCODESET=UTF8,utf8,57372;GL_USEGLU=1", "com.gbasedbt.jdbc.Driver", "dataserver", "root", "root", "gbase01")
		DB, err = gorm.Open(gbase.Open(dsn), &gorm.Config{})
	default:
		log.Fatal("不支持的驱动")
		return nil, fmt.Errorf("不支持的驱动")
	}

	if err != nil {
		return nil, err
	}

	// 自动迁移模式
	err = DB.AutoMigrate(&core.Conference{}, &core.ConferMember{})
	if err != nil {
		return nil, err
	}

	sqlDB, err := DB.DB()
	if err != nil {
		return nil, err
	}
	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(10)
	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(100)
	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Hour)

	return DB, nil
}

func main() {
	db, err := initDB()
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}
	//创建会议信息
	log.Println("创建会议信息")
	core.CreateConference(db, "1001", "101", "bxynj")

	//查询指定会议信息
	log.Println("查询指定会议信息")
	conferences, err := core.GetConferenceByField(db, "1001", "bxynj")
	if err != nil {
		log.Fatalf("Failed to get conference: %v", err)
		return
	}

	log.Println("会议信息列表")
	for _, conference := range conferences {
		fmt.Printf("Conference: %+v\n", conference)
	}

	log.Println("更新会议信息")
	core.UpdateConference(db, "1001", "doing")

	log.Println("删除会议信息")
	core.DeleteConference(db, 3)

}
